package org.javacore.base.copy;

/**
 * Created by Administrator on 2017/2/14.
 */

/**
 * @author Jeff Lee
 * @since 2015-11-16 13:53:51
 *  深拷贝与浅拷贝
 */
class Person implements Cloneable{
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * 深拷贝
     * @return
     */
    @Override
    public Object clone() {
        Object o = null;
        try {
            o = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return o;
    }
}
class Teacher implements Cloneable{
    private String name;
    private Person person;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    /**
     * 深拷贝
     * 不仅拷贝对象本身（包括对象中的基本变量），而且还拷贝对象包含的引用指向的对象
     */
    @Override
    protected Object clone() {
        Teacher o = null;
        try {
            o = (Teacher)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        o.person = (Person) person.clone();
        return o;
    }
}

public class DeepCopy1 {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName("Tom Family");
        Teacher t = new Teacher();
        t.setName("Tom");
        t.setPerson(p);
        Teacher teacher = (Teacher) t.clone();
        teacher.setName("Tom2");
        teacher.getPerson().setName("Tom2 Family");
        System.out.println(t.getName()+" "+ t.getPerson().getName());
        System.out.println(teacher.getName()+" "+ teacher.getPerson().getName());
    }
}
